package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

type ChapterHttp struct {
}

func main() {
	chapterHttp := ChapterHttp{}
	//reqUrl := "https://www.qq.com/"
	//err, done := chapterHttp.template(reqUrl)
	//printChapterError(err,"http请求模板方法报错,报错原因:")
	//if done {
	//	return
	//}

	//GET 请求
	//getExample := chapterHttp.getExample(err, reqUrl)
	//fmt.Println("getExample 成功没:",getExample)

	//post请求
	//chapterHttp.postExample(err, reqUrl)

	//启动web静态文件服务
	//chapterHttp.staticFileServer()
	// web服务核心原理,写个字符串返回给前端展示
	chapterHttp.coreWeb()

}

func (c *ChapterHttp) coreWeb() {
	//绑定路径后触发indexHandler
	http.HandleFunc("/index", indexHandler)
	// 第二个参数为nil的时候,使用默认的 http.defaultServeMux
	err := http.ListenAndServe("localhost:9090", nil)
	printChapterError(err, "核心原理,启动监听服务失败,失败原因:")
	//访问地址, http://localhost:9090/index
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
	_, err := w.Write([]byte("欢迎访问,这里是首页"))
	value := r.FormValue("name")
	fmt.Println("name == ", value)

	printChapterError(err, "indexHandler 写数据失败,失败原因:")
}

func (c *ChapterHttp) staticFileServer() {
	fileServer := http.FileServer(http.Dir("/Users/liuwx/Documents/project/go-demo/"))
	err := http.ListenAndServe(":9091", fileServer)
	printChapterError(err, "启动web静态文件服务报错,报错原因:")
}

func (c *ChapterHttp) postExample(err error, reqUrl string) {
	values := url.Values{"username": {"json"}}
	reader := strings.NewReader(values.Encode())
	postResponse, err := http.Post(reqUrl, "application/x-www-form-urlencoded", reader)
	printChapterError(err, "post请求失败,失败原因:")
	//post 处理数据同get
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			fmt.Println("读取post请求内容失败,失败原因:", err.Error())
		}
	}(postResponse.Body)
}

func (c *ChapterHttp) getExample(err error, reqUrl string) bool {
	getResponse, err := http.Get(reqUrl)
	printChapterError(err, "get 请求报错,报错原因:")
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			fmt.Println("关闭get请求失败,失败原因:", err.Error())
		}
	}(getResponse.Body)
	if getResponse.StatusCode == 200 {
		all, err := ioutil.ReadAll(getResponse.Body)
		if err != nil {
			fmt.Println("读取get请求内容失败,失败原因:", err.Error())
			return true
		}
		fmt.Println("get请求响应数据:", string(all))
	}
	return false
}

func (c *ChapterHttp) template(reqUrl string) (error, bool) {
	client := http.Client{}
	request, err := http.NewRequest(http.MethodGet, reqUrl, nil)
	printChapterError(err, "创建http请求失败")

	//设置cookie
	cookie := http.Cookie{Name: "username", Value: "project"}
	request.AddCookie(&cookie)

	//设置请求头
	request.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
	response, err := client.Do(request)
	printChapterError(err, "请求出错")
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			fmt.Println("关闭响应数据出错 ,错误原因 ", err.Error())
		}
	}(response.Body)

	fmt.Println("请求头数据 ", request.Header)
	fmt.Println("响应状态码 ", response.StatusCode)
	if response.StatusCode == 200 {
		body, err2 := ioutil.ReadAll(response.Body)
		if err2 != nil {
			printChapterError(err2, "读取响应信息失败,失败原因:")
			return nil, true
		}

		fmt.Println("返回数据:", string(body))
	} else {
		fmt.Println("请求失败,失败原因:", response.Status)
	}
	return err, false
}

func printChapterError(err error, msg string) {
	if err != nil {
		fmt.Println(msg, err.Error())
		return
	}
}
